package net.zjitc.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.zjitc.common.ResponseResult;
import net.zjitc.common.lang.Const;
import net.zjitc.common.page.OrderAndGoodPageData;
import net.zjitc.entity.Attribute;
import net.zjitc.entity.Goods;
import net.zjitc.entity.GoodsAttr;
import net.zjitc.entity.GoodsPics;
import net.zjitc.exception.GoodsException;
import net.zjitc.mapper.AttributeMapper;
import net.zjitc.mapper.GoodsAttrMapper;
import net.zjitc.mapper.GoodsMapper;
import net.zjitc.mapper.GoodsPicsMapper;
import net.zjitc.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 该service与数据库查询的次数较多,后面抽空缓存+xml优化
 *
 * @author 毛钰深
 * @create 2022/2/1
 */

@Service
@Transactional
@Slf4j
public class IGoodsService implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsPicsMapper goodsPicsMapper;

    @Autowired
    private GoodsAttrMapper goodsAttrMapper;

    @Autowired
    private AttributeMapper attributeMapper;

    @Override
    public ResponseResult selectPageGoods(String query, Integer pagenum, Integer pagesize) throws GoodsException {
        //判断参数是否正确
        if (pagenum == null || pagesize == null) {
            throw new GoodsException("所需参数传入为空");
        }
        Page<Goods> page = new Page<>(pagenum, pagesize);
        page = goodsMapper.selectPage(page, Wrappers.<Goods>lambdaQuery()
                .orderByDesc(Goods::getGoods_id)
                .like(query != null, Goods::getGoods_name, query)
                .select(Goods::getGoods_id,
                        Goods::getGoods_name,
                        Goods::getGoods_price,
                        Goods::getGoods_number,
                        Goods::getGoods_weight,
                        Goods::getGoods_state,
                        Goods::getAdd_time,
                        Goods::getUpd_time,
                        Goods::getHot_mumber,
                        Goods::getIs_promote));

        OrderAndGoodPageData<List> orderAndGoodPageData = new OrderAndGoodPageData<>();
        orderAndGoodPageData.setGoods(page.getRecords());
        orderAndGoodPageData.setPagenum(page.getCurrent());
        orderAndGoodPageData.setTotal(page.getTotal());

        ResponseResult res = new ResponseResult();
        res.setSuccess(orderAndGoodPageData);
        return res;
    }

    @Override
    public ResponseResult addGoods(Goods goods) throws GoodsException {
        if (goods.getGoods_name() == null ||
                goods.getGoods_cat() == null ||
                goods.getGoods_price() == null ||
                goods.getGoods_number() == null ||
                goods.getGoods_weight() == null) {
            throw new GoodsException("所需参数传入为空");
        }
        ResponseResult res = new ResponseResult();

        //防止传入其他字段造成bug
        Goods good = new Goods();
        good.setGoods_name(goods.getGoods_name());
        good.setGoods_price(goods.getGoods_price());
        good.setGoods_number(goods.getGoods_number());
        good.setGoods_weight(goods.getGoods_weight());
        good.setGoods_introduce(goods.getGoods_introduce());
        good.setPics(goods.getPics());
        good.setAttrs(goods.getAttrs());
        good.setAddTime((int) (System.currentTimeMillis() / 1000));
        good.setUpdTime((int) (System.currentTimeMillis() / 1000));
        //枚举类 0 未审核  1 审核中  2  已审核
        good.setGoodsState(0);

        good.setHotMumber(0);
        good.setIsPromote(false);

        //解析goods_cat,设置cat_one,two,three,以及cat_id
        String[] split = goods.getGoods_cat().split(",");
        List<Integer> collect = Arrays.stream(split).map(Integer::parseInt).collect(Collectors.toList());
        switch (collect.size()) {
            case 3:
                good.setCatThreeId(collect.get(2));
            case 2:
                good.setCatTwoId(collect.get(1));
            case 1:
                good.setCatOneId(collect.get(0));
                break;
        }

        if (collect.size() != 0) {
            good.setCatId(collect.get(0));
        } else {
            good.setCatId(0);
        }


        //判断该goods_name是否存在
        Goods one = goodsMapper.selectOne(Wrappers.<Goods>lambdaQuery().eq(Goods::getGoods_name, good.getGoods_name()));
        if (one!=null){
            throw new GoodsException("该商品名称已经存在");
        }

//        //判断是否为逻辑删除的数据
//        one = goodsMapper.selectOne(Wrappers.<Goods>lambdaQuery().eq(Goods::getGoods_name, good.getGoods_name()).eq(Goods::getIs_del,1));
//        if (one!=null){
//            //是被逻辑删除的数据时,恢复该数据,并且修改相关的添加参数
//
//
//            res.setCreated("创建商品成功", good);
//            return res;
//        }

        int insert;
        //添加完后,goods_id才会回填
        insert = goodsMapper.insert(good);
        if (insert == 0) {
            throw new GoodsException("创建商品失败");
        }

        //添加pics和attrs的数组
        //处理pics
        if (good.getPics() != null && good.getPics().size() != 0) {
            setPicsValue(good.getGoods_id(), good.getPics());
            insert = goodsPicsMapper.insertBatchSomeColumn(good.getPics());
            if (insert == 0) {
                throw new GoodsException("添加商品图片失败");
            }
        }

        //处理attrs
        List<GoodsAttr> attrs = good.getAttrs();
        if (attrs != null && attrs.size() != 0) {
            for (GoodsAttr attr : attrs) {
                attr.setGoods_id(good.getGoods_id());
            }
            insert = goodsAttrMapper.insertBatchSomeColumn(attrs);
            if (insert == 0) {
                throw new GoodsException("添加商品属性失败");
            }
            //处理每一个元素中的Attribute的值
            setAttributeToGoodsAttr(attrs);
        }


        res.setCreated("创建商品成功", good);
        return res;
    }

    @Override
    public ResponseResult selectById(Integer id) throws GoodsException {
        ResponseResult res = new ResponseResult();
        Goods goods = goodsMapper.selectById(id);
        if (goods == null) {
            throw new GoodsException("商品不存在");
        }

        List<GoodsPics> pics = goodsPicsMapper.selectList(Wrappers.<GoodsPics>lambdaQuery().eq(GoodsPics::getGoods_id, goods.getGoods_id()));
        goods.setPics(pics);

        List<GoodsAttr> attrs = goodsAttrMapper.selectList(Wrappers.<GoodsAttr>lambdaQuery().eq(GoodsAttr::getGoods_id, goods.getGoods_id()));

        setAttributeToGoodsAttr(attrs);

        goods.setAttrs(attrs);
        goods.setCatId(null);

        res.setSuccess(goods);
        return res;
    }

    /**
     * 设置GoodsAttr对象中Attribute变量对应的属性
     * @param attrs
     * @throws GoodsException
     */
    private void setAttributeToGoodsAttr(List<GoodsAttr> attrs) throws GoodsException {
        List<Integer> attrIds = new ArrayList<>();
        attrs.forEach(a -> {
            attrIds.add(a.getAttr_id());
        });
        List<Attribute> attributes = attributeMapper.selectList(Wrappers.<Attribute>lambdaQuery().in(Attribute::getAttr_id, attrIds));
        if (attributes == null) {
            throw new GoodsException("attr_id在分类参数中不存在");
        }
        attributes.forEach(a -> {
            attrs.forEach(attr -> {
                if (a.getAttr_id().equals(attr.getAttr_id())) {
                    a.setCat_id(null);
                    attr.setAttribute(a);
                    //attr.setId(null);
                }
            });
        });
    }

    @Override
    public ResponseResult updateGoods(Goods goods) throws GoodsException {
        if (goods.getGoods_name() == null ||
                goods.getGoods_price() == null ||
                goods.getGoods_number() == null ||
                goods.getGoods_weight() == null) {
            throw new GoodsException("必须传入的参数为空");
        }

        ResponseResult res = new ResponseResult();

        //查询商品是否存在
        Goods good = goodsMapper.selectById(goods.getGoods_id());
        if (good == null) {
            throw new GoodsException("修改的商品不存在");
        }

        //先执行删除图片操作
        //获取所有的待修改id,删除除了待修改id外的所有图片
        List<GoodsPics> goodsPics = goodsPicsMapper.selectList(Wrappers.lambdaQuery(GoodsPics.class).eq(GoodsPics::getGoods_id, goods.getGoods_id()));
        List<Integer> picsId=new ArrayList<>();
        for (GoodsPics pic : goodsPics) {
            for (GoodsPics goodsPic : goods.getPics()) {
                if (pic.getPics_id().equals(goodsPic.getPics_id())){
                    picsId.add(pic.getPics_id());
                }
            }
        }

        int delete = goodsPicsMapper.delete(Wrappers.lambdaQuery(GoodsPics.class).eq(GoodsPics::getGoods_id, good.getGoods_id()).notIn(picsId.size()!=0,GoodsPics::getPics_id,picsId));
        log.info("删除了"+delete+"条图片记录");

        good.setGoodsName(goods.getGoods_name());
        good.setGoodsPrice(goods.getGoods_price());
        good.setGoodsNumber(goods.getGoods_number());
        good.setGoodsWeight(goods.getGoods_weight());
        good.setGoodsIntroduce(goods.getGoods_introduce());
        good.setPics(goods.getPics());
        good.setAttrs(goods.getAttrs());
        String[] split = goods.getGoods_cat().split(",");
        good.setCatOneId(Integer.parseInt(split[0]));
        good.setCatTwoId(Integer.parseInt(split[1]));
        good.setCatThreeId(Integer.parseInt(split[2]));

        int update = goodsMapper.updateById(good);
        if (update == 0) {
            throw new GoodsException("修改失败");
        }

        //修改pics和attrs并返回

        //处理pics列表
        setPicsValue(good.getGoods_id(), good.getPics());
        //区分是新添加的图片还是已存在的图片修改
        List<GoodsPics> newPics=new ArrayList<>();
        List<GoodsPics> oldPics=new ArrayList<>();
        for (GoodsPics pic : good.getPics()) {
            if (pic.getPics_id()==null){
                newPics.add(pic);
            }else{
                oldPics.add(pic);
            }
        }
        //对应处理
        if (oldPics.size()!=0){
            goodsPicsMapper.updateBatchSomeColumn(oldPics);
        }
        if (newPics.size()!=0){
            goodsPicsMapper.insertBatchSomeColumn(newPics);
        }

        //attrs的处理,全部删除之后再进行添加
        List<GoodsAttr> attrs = good.getAttrs();
        for (GoodsAttr attr : attrs) {
            if (attr.getAttr_value() == null || "".equals(attr.getAttr_value())){
                throw new GoodsException("传入参数错误!");
            }
            attr.setGoods_id(good.getGoods_id());
        }

        //删除原有的数据库数据
        int delete1 = goodsAttrMapper.delete(Wrappers.lambdaQuery(GoodsAttr.class).eq(GoodsAttr::getGoods_id,good.getGoods_id()));
        log.info("删除了"+delete1+"条属性数据");

        //添加进数据库中
        if (attrs.size() != 0){
            update = goodsAttrMapper.insertBatchSomeColumn(attrs);
        }
        setAttributeToGoodsAttr(attrs);


        res.setSuccess("修改商品成功", good);
        return res;
    }

    @Override
    public ResponseResult deleteById(Integer id) {
        ResponseResult res = new ResponseResult();
        int deleteById = goodsMapper.deleteById(id);
        if (deleteById != 0) {
            //删除相关的attr和pic
            goodsPicsMapper.delete(Wrappers.<GoodsPics>lambdaQuery().eq(GoodsPics::getGoods_id, id));
            goodsAttrMapper.delete(Wrappers.<GoodsAttr>lambdaQuery().eq(GoodsAttr::getGoods_id, id));
            res.setSuccess("删除成功");
        } else {
            res.setError("商品不存在");
        }
        return res;
    }

    private void setPicsValue(Integer goodId, List<GoodsPics> pics) throws GoodsException {
        for (GoodsPics pic : pics) {
            if (pic.getPics_id() == null && pic.getPic() == null) {
                throw new GoodsException("传入的图片的id值或pic路径值为空,不能进行修改");
            }
            if (pic.getPic() != null) {
                String p = pic.getPic();
                pic.setPic(null);
                String[] split = p.split("/");
                if (split.length != 2) {
                    throw new GoodsException("传入的pic不符合要求");
                }
                pic.setPicsBig(split[0] + "/" + Const.IMAGE_BIG + split[1]);
                pic.setPicsMid(split[0] + "/" + Const.IMAGE_MID + split[1]);
                pic.setPicsSma(split[0] + "/" + Const.IMAGE_SMA + split[1]);
            }
            pic.setGoodsId(goodId);
        }
    }

    @Override
    public ResponseResult updatePics(Integer id, List<GoodsPics> pics) throws GoodsException {
        Goods goods = goodsMapper.selectById(id);
        if (goods == null) {
            throw new GoodsException("该商品不存在");
        }
        ResponseResult res = new ResponseResult();
        List<GoodsPics> insert = new ArrayList<>();
        List<GoodsPics> update = new ArrayList<>();

        //处理
        setPicsValue(id, pics);
        pics.forEach(p -> {
            if (p.getPics_id() == null) {
                //添加,图片,并且设置相关参数
                insert.add(p);
            } else {
                //修改图片
                update.add(p);
            }
        });

        //批量插入
        if (insert.size() != 0) {
            int i = goodsPicsMapper.insertBatchSomeColumn(insert);
            if (i == 0) {
                throw new GoodsException("同步图片失败");
            }
        }

        //批量修改
        if (update.size() != 0) {
            int u = goodsPicsMapper.updateBatchSomeColumn(update);
            if (u == 0) {
                throw new GoodsException("同步图片失败");
            }
        }

        List<GoodsPics> pic = goodsPicsMapper.selectList(Wrappers.<GoodsPics>lambdaQuery().eq(GoodsPics::getGoods_id, goods.getGoods_id()));
        goods.setPics(pic);

        List<GoodsAttr> attrs = goodsAttrMapper.selectList(Wrappers.<GoodsAttr>lambdaQuery().eq(GoodsAttr::getGoods_id, goods.getGoods_id()));
        setAttributeToGoodsAttr(attrs);

        goods.setAttrs(attrs);
        goods.setCatId(null);
        res.setSuccess("更新成功", goods);
        return res;
    }


}
